package cn.itcast.demo;
//  反射获取参数
import cn.itcast.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.PropertyPermission;
import java.util.Set;

@WebServlet("/ServletDemo03")
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.根据名称获取数据
        Map<String, String[]> map = req.getParameterMap();
        Student stu = new Student();
        for (String key :map.keySet()){
            String[] values = map.get(key);
            try {
//                获取Student对象的属性描述器
                PropertyDescriptor pd = new PropertyDescriptor(key,stu.getClass());
//                获取对应的方法
                Method writeMethod = pd.getWriteMethod();
//                执行方法
                if (values.length > 1){
                    writeMethod.invoke(stu,(Object) values);
                }else if (values.length == 1) {
                    writeMethod.invoke(stu, values);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(stu);
       
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
